﻿using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using System;

namespace My.Admin.Controllers
{
	/// <summary>
	/// CAP 使用示例
	/// </summary>
	[ApiController]
	[Route("[controller]")]
	public class PublishController : ControllerBase
	{
		private readonly ICapPublisher _capBus;

		public PublishController(ICapPublisher capPublisher)
		{
			_capBus = capPublisher;
		}

		/// <summary>
		/// 发送消息
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		[Route("Send")]
		public string SendMessage()
		{
			_capBus.Publish("test.show.time", DateTime.Now);

			return "Ok";
		}

		/// <summary>
		/// 发送延迟消息
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		[Route("DelaySend")]
		public string SendDelayMessage()
		{
			_capBus.PublishDelay(TimeSpan.FromSeconds(100), "test.show.time", DateTime.Now);

			return "Ok";
		}

		/// <summary>
		/// 发送包含头信息的消息
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		[Route("SendHeader")]
		public string SendHeaderMessage()
		{
			var header = new Dictionary<string, string>()
			{
				["my.header.first"] = "first",
				["my.header.second"] = "second"
			};

			_capBus.Publish("test.show.time.header", DateTime.Now, header);

			return "Ok";
		}

		/// <summary>
		/// 处理消息
		/// </summary>
		/// <param name="time"></param>
		[NonAction]
		[CapSubscribe("test.show.time")]
		public void ReceiveMessage(DateTime time)
		{
			Console.WriteLine("message time is:" + time);
		}

		/// <summary>
		/// 处理包含头信息的消息
		/// </summary>
		/// <param name="time"></param>
		/// <param name="header"></param>
		[NonAction]
		[CapSubscribe("test.show.time.header")]
		public void ReceiveMessage(DateTime time, [FromCap] CapHeader header)
		{
			Console.WriteLine("message time is:" + time);
			Console.WriteLine("message firset header :" + header["my.header.first"]);
			Console.WriteLine("message second header :" + header["my.header.second"]);
		}
	}
}
